<?php
/**
 * Classe per la gestione della sessione Facebook
 * @author rbutti
 *
 */
class IltsFacebook {
  private static $instance;

  private $facebookApiId;
  private $facebookAppSecret;
  private $facebook;
  private $me;
  private $uid;


  private function __construct()
  {
    $this->facebookApiId = sfConfig::get("app_facebook_app_id");
    $this->facebookAppSecret = sfConfig::get("app_facebook_app_secret");
    $this->facebook = new Facebook(array(
      'appId'  => $this->facebookApiId,
      'secret' => $this->facebookAppSecret,
      'cookie' => true,
    ));
    $this->me = null;
    $this->uid = "";

    // Session based API call.
    if ($this->getSession()) {
      try {
        $this->uid = $this->facebook->getUser();
        $this->me = $this->facebook->api('/me');
      } catch (FacebookApiException $e) {
        
        //echo ($e);
      }
    }
    // login or logout url will be needed depending on current user state.
    if ($this->me) {
      $this->logoutUrl = $this->facebook->getLogoutUrl();
    } else {
      $this->loginUrl = $this->facebook->getLoginUrl();
    }
  }

  // The singleton method
  public static function getInstance()
  {
    if (!isset(self::$instance)) {
      $c = __CLASS__;
      self::$instance = new $c;
    }
    return self::$instance;
  }

  public function getFacebook() {
    return $this->facebook;
  }

  public function getSession() {
    return $this->getFacebook()->getSession();
  }

  public function getLogoutUrl() {
    $logoutUrl = "";
    if ($this->me) {
      $logoutUrl = $this->getFacebook()->getLogoutUrl();
    }
    return $logoutUrl;
  }

  public function getLoginUrl() {
    $loginUrl = "";
    if ($this->me) {
      $loginUrl = "";
    } else {
      $loginUrl = $this->getFacebook()->getLoginUrl();
    }
    return $loginUrl;
  }
  
  public function getRedirectUrl() {
    $returnLink = "http://apps.facebook.com/ilts_dev/";
    $urlStep = "https://graph.facebook.com/oauth/authorize";
    $scope = "";
    $scope = "user_photos,user_videos,publish_stream,read_insights,offline_access";
    $redirectUrl = $urlStep."?client_id=".$this->facebookApiId;
    $redirectUrl= $redirectUrl."&redirect_uri=".$returnLink;
    return $redirectUrl;
  }
  public function isAppAdded() {
    $bRetVal = false;
    if ($this->me) {
      $bRetVal = true;
    }
    return $bRetVal;
  }
  
  public function getUid() {
    return $this->uid;
  }
  
  public function isUserAuthenticated() {
    return ($this->uid != "");
  }
  
  public function getMe() {
    return $this->me;
  }
  
  public function getProfileName() {
    $name = "";
    if ($this->me != null) {
      $name = $this->me["name"];
    }
    return $name;
  }
  
  public function getApplicationId() {
    return $this->facebookApiId;
  }





}